package org.grow.prac.service;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: xwg
 * @CreateDate: 2023/9/20
 */

@Service
public class JwtService {

//@VAlue
    private Integer expireMinutes = 30;
    private String secret = "abcdefghijklmnopqrstuvwxyz0123456789";


    private Key key;
    private JwtParser jwtParser;
    @PostConstruct
    public void init(){
        key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
        JwtParserBuilder parserBuilder = Jwts.parserBuilder();
        parserBuilder.setSigningKey(key);
        jwtParser = parserBuilder.build();
    }
    public String createToken(Map<String, Object> data) {
        JwtBuilder builder = Jwts.builder();
//        header
        builder.setHeaderParam("typ", "jwt");
//      body
        long start = System.currentTimeMillis();
        long end = start + expireMinutes * 60 * 1000;
        builder.setIssuedAt(new Date(start));
        builder.setExpiration(new Date(end));
//        添加主题
        builder.setSubject("auth");
//        添加当前登录
        builder.addClaims(data);
//签名 防止篡改

        builder.signWith(key, SignatureAlgorithm.HS256);
        return builder.compact();
    }

    public Map<String, Object> parseToken(String token){
        try {
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            return body;
        } catch (SignatureException e) {
            System.out.println("jwt token 被从篡改过，不值得信任"+e.getMessage());
            throw e;
        } catch (ExpiredJwtException e) {
            System.out.println("jwt token 过期了，请重新申请"+e.getMessage());
            throw e;
        }  catch (JwtException e) {
            System.out.println("未知 jwt  异常"+e.getMessage());
            throw e;
        }

    }
}
